<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="仓库" prop="warehouseId">
            <WarehouseSelect v-model:wh-id="pd.queryParams.warehouseId" placeholder="请选择仓库"
                             @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="产品" prop="productId">
            <StockSearch title="产品查询" v-model:data-text="pd.productName" @ok="selected" />
          </el-form-item>
          <el-form-item label="更新时间" style="width: 290px">
            <el-date-picker
              v-model="dateRangeUpdateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:stockLog:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()" v-hasPermi="['wms:stockLog:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()" v-hasPermi="['wms:stockLog:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:stockLog:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.stockLogList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="事务ID" align="center" prop="id" />
        <el-table-column label="物品名" align="center" prop="productName" />
        <el-table-column label="物品id" align="center" prop="productId" />
        <el-table-column label="单位" align="center" prop="measureUnit" />
        <el-table-column label="批次号" align="center" prop="batchCode" />
        <el-table-column label="单据号" align="center" prop="orderId" />
        <el-table-column label="单价" align="center" prop="price" />
        <el-table-column label="仓库名" align="center" prop="warehouseName" />
        <el-table-column label="库位ID" align="center" prop="areaId" />
        <el-table-column label="操作前" align="center" prop="quantityBefore" />
        <el-table-column label="操作后" align="center" prop="quantityAfter" />
        <el-table-column label="操作数量" align="center" :formatter="formatQuantity"/>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="更新者" align="center" prop="updateBy" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['wms:stockLog:edit']"> 修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['wms:stockLog:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改出入库记录台账对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
      <el-form ref="stockLogFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-form-item label="物品id" prop="productId">
          <el-input v-model="pd.form.productId" placeholder="请输入物品id" />
        </el-form-item>
        <el-form-item label="单位" prop="measureUnit">
          <el-input v-model="pd.form.measureUnit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchCode">
          <el-input v-model="pd.form.batchCode" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="单据号" prop="orderId">
          <el-input v-model="pd.form.orderId" placeholder="请输入单据号" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="pd.form.price" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="仓库ID" prop="warehouseId">
          <el-input v-model="pd.form.warehouseId" placeholder="请输入仓库ID" />
        </el-form-item>
        <el-form-item label="库位ID" prop="areaId">
          <el-input v-model="pd.form.areaId" placeholder="请输入库位ID" />
        </el-form-item>
        <el-form-item label="操作前" prop="quantityBefore">
          <el-input v-model="pd.form.quantityBefore" placeholder="请输入操作前" />
        </el-form-item>
        <el-form-item label="操作数量" prop="quantity">
          <el-input v-model="pd.form.quantity" placeholder="请输入操作数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StockLog" lang="ts">
import {StockLogVO, listStockLog, getStockLog, delStockLog, addStockLog, updateStockLog } from '@/views/wms/stockLog/api';
import WarehouseSelect from "@/views/wms/warehouse/select.vue";
import StockSearch from "@/views/wms/stock/search.vue";
import {StockVO} from "@/views/wms/stock/api";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);


const queryFormRef = ref<ElFormInstance>();
const stockLogFormRef = ref<ElFormInstance>();

const initFormData: StockLogVO = {
  pageNum: 0, pageSize: 0,
  productId: undefined,
  measureUnit: undefined,
  batchCode: undefined,
  orderId: undefined,
  price: undefined,
  warehouseId: undefined,
  areaId: undefined,
  quantityBefore: undefined,
  quantity: undefined,
  remark: undefined
}
const pd = reactive({
  stockLogList: <StockLogVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <StockLogVO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  productName: "",
  form: <StockLogVO>{...initFormData},
  queryParams: <StockLogVO>{
    pageNum: 1,
    pageSize: 10,
    productId: undefined,
    batchCode: undefined,
    price: undefined,
    warehouseId: undefined,
    params: {
    }
  },
  rules: <ElFormRules>{
    productId: [
      { required: true, message: "物品id不能为空", trigger: "blur" }
    ],
    measureUnit: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ],
    batchCode: [
      { required: true, message: "批次号不能为空", trigger: "blur" }
    ],
    orderId: [
      { required: true, message: "单据号不能为空", trigger: "blur" }
    ],
    price: [
      { required: true, message: "单价不能为空", trigger: "blur" }
    ],
    warehouseId: [
      { required: true, message: "仓库ID不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "操作数量不能为空", trigger: "blur" }
    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});


/** 查询出入库记录台账列表 */
async function getList() {
  pd.loading = true;
  proxy?.addDateRange(pd.queryParams, dateRangeUpdateTime.value, 'CreateTime');
  const res = await listStockLog(pd.queryParams);
  pd.stockLogList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {...initFormData};
  stockLogFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  pd.productName = "";
  dateRangeUpdateTime.value = ['', ''];
  queryFormRef.value!.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: StockLogVO[]) {
  pd.selectVO = selection;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加出入库记录台账";
}

/** 修改按钮操作 */
async function handleUpdate(row?: StockLogVO) {
  reset();
  const data = row || pd.selectVO[0]
  Object.assign(pd.form, data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改出入库记录台账";
}

/** 提交按钮 */
function submitForm() {
  stockLogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateStockLog(pd.form).finally(() =>  pd.buttonLoading = false);
      } else {
        await addStockLog(pd.form).finally(() =>  pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: StockLogVO) {
  const _ids = row?.id || pd.selectVO.map(v => v.id);
  await proxy?.$modal.confirm('是否确认删除出入库记录台账编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delStockLog(<number | number[]>_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/stockLog/export', {
    ...pd.queryParams
  }, `stockLog_${new Date().getTime()}.xlsx`)
}

function formatQuantity(row: any){
  const quantityBefore = row.quantityBefore || 0;
  const quantityAfter = row.quantityAfter || 0;
  return Math.abs(quantityBefore - quantityAfter);
}

async function selected(vo: StockVO[]){
  vo.forEach((v)=>{
    pd.queryParams.productId = v.productId;
    pd.productName = v.productName!;
  })
}

onMounted(() => {
  getList();
});
</script>
